package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.ProductBrandMapper;
import com.example.crossborderecommerce.service.IAdminService;
import com.example.crossborderecommerce.service.ILogService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 日志模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/log")
public class LogController {
    @Resource
    ILogService logService;
    @Resource
    IAdminService adminService;

    /**
     * 添加日志
     * @param log
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Log log){
        boolean res = logService.save(log);
        if(res){
            return Result.success("添加日志成功！");
        }
        return Result.error("添加日志失败！");
    }

    /**
     * 删除日志
     * @param log
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Log log){
        boolean res = logService.removeById(log);
        if(res){
            return Result.success("删除日志成功！");
        }
        return Result.error("删除日志失败！");
    }

    /**
     * 删除一系列日志
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> logIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = logService.removeByIds(logIds);
        if(res) {
            return Result.success("删除日志成功！");
        }
        return Result.error("删除日志失败！");
    }

    /**
     * 修改日志
     * @param log
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Log log) {
        boolean res = logService.saveOrUpdate(log);
        if (res) {
            return Result.success("修改日志成功！");
        }
        return Result.error("修改日志失败！");
    }


    /**
     * 分页查询所有操作日志
     * @param adminId
     * @param type
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "-1") String adminId,
                           @RequestParam(defaultValue = "全部") String type,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        if(!type.equals("全部")) {
            queryWrapper.eq("type", type);
        }
        if(!adminId.equals("-1")) {
            queryWrapper.eq("admin_id", adminId);
        }
        Page<Log> adminPage = logService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Log> logList = adminPage.getRecords();
        for(Log log : logList) {
            if(log.getAdminId() != null) {
                Admin admin = adminService.getById(log.getAdminId());
                log.setAdminName(admin.getName());
            }
        }
        return Result.success("成功查询所有操作日志！",adminPage);
    }
    /**
     * 导出系统日志
     * @param adminId
     * @param type
     * @param response
     * @return
     */
    @GetMapping("exportLogList")
    public Result exportLogList(@RequestParam(defaultValue = "-1") String adminId,
                                @RequestParam(defaultValue = "全部") String type,
                                         HttpServletResponse response) {
        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        if(!type.equals("全部")) {
            queryWrapper.eq("type", type);
        }
        if(!adminId.equals("-1")) {
            queryWrapper.eq("admin_id", adminId);
        }
        List<Log> logList = logService.list(queryWrapper);
        for(Log log : logList) {
            if(log.getAdminId() != null) {
                Admin admin = adminService.getById(log.getAdminId());
                log.setAdminName(admin.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("操作人");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("操作人角色");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("异常类型");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("报错内容");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("操作时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < logList.size(); i++) {
            row = sheet.createRow(i + 1);
            Log log = logList.get(i);
            row.createCell((short) 0).setCellValue(log.getId());
            row.createCell((short) 1).setCellValue(log.getAdminName());
            row.createCell((short) 2).setCellValue(log.getAdminRole());
            row.createCell((short) 3).setCellValue(log.getType());
            row.createCell((short) 4).setCellValue(log.getContent());
            try {
                Date createTime = inputDateFormat.parse(log.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 5).setCellValue(outputDateFormat.format(createTime));
            } catch (ParseException e) {
                row.createCell((short) 5).setCellValue(log.getCreateTime().toString());
            }
        }
        String fileName = "exportLogList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductBrandList");
    }
}


